﻿
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;
using System.Collections;
using System.Xml;
using System.Xml.Linq;
namespace Intel_Client_GUI
{
    public class DataBaseWrap
    {
        public DataBaseWrap()
		{
            DbName = "database.db";
            InitialConnection();                //初始化数据库连接
        }
		
        public DataTable GetQueryTable(string QueryName)
        {
			try
			{
				var Cmd = connection.CreateCommand();
				//System.Windows.Forms.MessageBox.Show(QueryName);
				Cmd.CommandText = QueryName;
				Adapter.SelectCommand = Cmd;
				DataSet ds = new DataSet();
				ds.Tables.Add("Result");
				ds.EnforceConstraints = false;
				Adapter.FillSchema(ds,SchemaType.Mapped,"Result");
				Adapter.Fill(ds,"Result");
				//System.Windows.Forms.MessageBox.Show(ds.Tables["Result"].Columns[0].DataType.ToString());
				return ds.Tables["Result"];
			}
			catch(System.Exception ex)
			{
				System.Windows.MessageBox.Show(ex.Message);
				return null;
			}
        }
		
		
		public DataTable GetQueryTable(string QueryName,DateTime start,TimeSpan duration)
        {
			try
			{
				var Cmd = connection.CreateCommand();
				//System.Windows.Forms.MessageBox.Show(QueryName);
				QueryName = QueryName.Replace("timetick"," timestamp>'"+ start.ToString("yyyy-MM-dd hh:mm:ss") + "' and timestamp <'"+(start+duration).ToString("yyyy-MM-dd hh:mm:ss")+"'");
				Cmd.CommandText = QueryName;
				//System.Windows.MessageBox.Show(Cmd.CommandText);
				Adapter.SelectCommand = Cmd;
				DataSet ds = new DataSet();
				ds.Tables.Add("Result");
				ds.EnforceConstraints = false;
				Adapter.FillSchema(ds,SchemaType.Mapped,"Result");
				Adapter.Fill(ds,"Result");
				//System.Windows.Forms.MessageBox.Show(ds.Tables["Result"].Columns[0].DataType.ToString());
				return ds.Tables["Result"];
			}
			catch(System.Exception ex)
			{
				System.Windows.MessageBox.Show(ex.Message);
				return null;
			}
        }


        #region Initialization
        private void InitialConnection()
        {
            connection = new SQLiteConnection("Data Source=" + DbName + ";Pooling=true;FailIfMissing=true");
        }     //初始化连接信息

        #endregion

        #region  Fields
        private string DbName;                   //数据库名
        private SQLiteConnection connection;                        //数据库连接
        private SQLiteDataAdapter Adapter = new SQLiteDataAdapter();//数据库适配器

        #endregion
    }
}
